<?php
/**
 * CreateTime: 2023/8/15 14:29
 */

namespace App\Http\Controllers\MeSendLetter;

use App\Consts\BaseConsts\BaseConsts;
use App\Consts\MeLawCaseConsts\MeLawCaseLetterConsts;
use App\Consts\MeLawCaseConsts\MeLawCaseListConsts;
use App\Consts\ResponseConsts\ResponseStatusConsts;
use App\Consts\TableConsts\TableConsts;
use App\Func\AppFunc;
use App\Func\LetterFunc;
use App\Func\ResponseFunc;
use App\Func\SMSFunc;
use App\Func\TokenFuc;
use App\Http\Requests\ListBasicRequest;
use App\Models\LatterCache\MeSendLatterCacheModel;
use App\Models\LatterCache\MeSendLetterCacheBindModel;
use App\Models\MeClient\MeClientModel;
use App\Models\MeLawCase\MeLawCase;
use App\Models\MeLawCase\MeLawCaseLawLetterModel;
use App\Models\MeLawCase\MeLawCasePhoneModel;
use App\Models\SMS\SMSTemp;
use App\Scopes\MediationStaffScope;
use App\Tools\ShortLink\ShortLinkFunc;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Storage;
use PHPUnit\Exception;

class AdminMeSendLetterController
{

    public function getPreviewCaseInfo($letterCacheId){
        $letterCacheInfo = (new MeSendLatterCacheModel())->getAllById($letterCacheId,[
            'letter_ids',
            'preview_info'
        ]);

        if(!$letterCacheInfo){
            return ResponseFunc::returnJson(
                'error',
                null,
                '当前缓存不存在',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }

        if($letterCacheInfo['preview_info']){
            $returnData = json_decode($letterCacheInfo['preview_info'],true);
            // 取出所有图片
            $images = Storage::disk('local')->files($returnData['images']);
            $reqImages = [];
            foreach ($images as $image) {
                // 获取图片内容并进行 base64 编码
                $base64Image = base64_encode(Storage::disk('local')->get($image));
                // 输出 base64 编码后的图片
                $reqImages[] = "data:image/png;base64,".$base64Image;
            }
            return ResponseFunc::returnJson(
                'ok',
                [
                    'images' => $reqImages,
                    'phone' => $returnData['phone'],
                    'sms_content' => $returnData['sms_content'],
                    'law_case_basic' => $returnData['law_case_basic']
                ],
                '获取预览审批成功',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }

        $lawCaseArr = explode(',',$letterCacheInfo['letter_ids']);
        $len = count($lawCaseArr);
        $lawCaseId = $lawCaseArr[rand(0,$len-1)];

        $lawCaseModel = new MeLawCase();
        // 查询案件详情
        $req = $lawCaseModel->select(
            [
                'law_case.*',
                'client.client_id',
                'client.client_name',
                'file.file_name as client_temp_law_filename',
                'client.client_code',
                'law_case_phone.phone_number'
            ]
        )
            ->leftjoin(TableConsts::ME_CLIENT." as client",'client.client_id','law_case.client_id')
            ->leftjoin(TableConsts::CY_FILE_TABLE_NAME." as file",'client.client_temp_law_not_sign_file_id','file.file_id')
            ->leftjoin(TableConsts::ME_LAW_CASE_PHONE." as law_case_phone",'law_case_phone.law_case_phone_id','law_case.main_respondent_phone_id')
            ->withoutGlobalScope(MediationStaffScope::class)
            ->where('law_case.law_case_id',$lawCaseId)
            ->where('law_case.status',BaseConsts::STATUS_NORMAL)
            ->where('law_case.is_send_law_latter',2)
            ->first();
        if($req){

            $templateArray = $req->toArray();
            $lawCaseCustomArray = json_decode($templateArray['law_case_custom'],true);
            // 解开自定义字段并且合并数组
            unset($templateArray['law_case_custom']);
            if(!$lawCaseCustomArray){
                $lawCaseCustomArray = [];
            }

            $templateDisposeArray = array_merge($templateArray,$lawCaseCustomArray);
            // 通过客户ID和数组设置默认字段
            // 生成电子函
            $templateDisposeArray = (new LetterFunc())->setDefaultFiledByClient($req['client_id'],$templateDisposeArray,1);
            // 生成文件
            if(!$req['client_temp_law_filename']){
                return ResponseFunc::returnJson(
                    'error',
                    null,
                    '预览失败,函件模板错误',
                    ResponseStatusConsts::OK_200_RESPONSE_STATUS
                );
            }
            $imgInfo = (new LetterFunc())->createdWord(json_encode($templateDisposeArray,256),$req['client_temp_law_filename'],false);

            if($imgInfo) {
//                echo "进入模板生成\n";
                // 根据案件文件hash 和count 生成唯一地址 这里随便给了一个count
                $shortInfo = ShortLinkFunc::coverShortUrl(AppFunc::getSystemConfig()::LATTER_REDIRECT_URL . "checker?id=" . $imgInfo['pdf_hash'], 1);
                // 添加调解函库
                $meLawCaseLawLetter = new MeLawCaseLawLetterModel();
                $addLawLatterReq = $meLawCaseLawLetter->add([
                    'law_case_id' => (int)$lawCaseId,
                    'client_id' => $req['client_id'],
                    'latter_nums' => $templateDisposeArray['nums'],
                    'law_case_id_card' => $templateArray['respondent_id_card'],
                    'pdf_water_path' => $imgInfo['pdf_water_path'],
                    'pdf_path' => $imgInfo['pdf_path'],
                    'pdf_path_hash' => $imgInfo['pdf_hash'],
                    'file_image_dir' => $imgInfo['image_group'],
                    'short_link_id' => $shortInfo['res_id'],
                ],true);
                $lawCasePhoneModel = new MeLawCasePhoneModel();
                $tempModel = new SMSTemp();
                // 查询模板
                $tempInfo = $tempModel->where('sms_temp_id', 10)->first();
                $tempStr = "";
                if ($tempInfo && isset($tempInfo['temp_content'])) {
                    $tempStr = $tempInfo['temp_content'];
                }
                $messageList = [];
                $smsLogList = [];
                // 获取主叫号码
                $lawCaseInfo = $lawCaseModel->getByIdNotCompanyNotStatus($lawCaseId, ['law_case_id', 'respondent_name', 'client_id', 'main_respondent_phone_id']);
                $tempContent = (new SMSFunc())->replaceTemp($lawCaseInfo, $tempStr);
                $phoneModel = new MeLawCasePhoneModel();
                $phone = $phoneModel->getByIdNotCompany($lawCaseInfo['main_respondent_phone_id'],['phone_number']);
                if(!isset($phone['phone_number'])){
                    return ResponseFunc::returnJson(
                        'error',
                        null,
                        '预览失败,手机格式错误',
                        ResponseStatusConsts::OK_200_RESPONSE_STATUS
                    );
                }
                $phone = $phone['phone_number'];

                // 删除掉这条测试用的调解函
                $meLawCaseLawLetter->withoutGlobalScope(MediationStaffScope::class)->where('law_case_law_letter_id',$addLawLatterReq)->delete();
                if (!$tempContent) {
                    return ResponseFunc::returnJson(
                        'error',
                        null,
                        '预览失败,短信模板错误',
                        ResponseStatusConsts::OK_200_RESPONSE_STATUS
                    );
                }
                // 取出所有图片
                $images = Storage::disk('local')->files($imgInfo['image_group']);
                $reqImages = [];
                foreach ($images as $image) {
                    // 获取图片内容并进行 base64 编码
                    $base64Image = base64_encode(Storage::disk('local')->get($image));
                    // 输出 base64 编码后的图片
                    $reqImages[] = "data:image/png;base64,".$base64Image;
                }
                // 修改当前预览信息 避免冲生成
                $letterCacheInfo->where('send_letter_cache_id',$letterCacheId)->update([
                    'preview_info'=>json_encode([
                        'images' => $imgInfo['image_group'],
                        'phone' => $phone,
                        'sms_content' => $tempContent,
                        'law_case_basic' => $req->toArray()
                    ],256)
                ]);


                return ResponseFunc::returnJson(
                    'ok',
                    [
                        'images' => $reqImages,
                        'phone' => $phone,
                        'sms_content' => $tempContent,
                        'law_case_basic' => $req->toArray()
                    ],
                    '审批信息获取成功',
                    ResponseStatusConsts::OK_200_RESPONSE_STATUS
                );
            }else{
                return ResponseFunc::returnJson(
                    'error',
                    null,
                    '预览失败,函件模板错误2',
                    ResponseStatusConsts::OK_200_RESPONSE_STATUS
                );
            }
        }

    }

    public function getSendLetterList(ListBasicRequest $request){
        $pFilters = $request->get('filters');
        $pageSize = $request->get('page_size');
        $filters = $pFilters ? json_decode($pFilters, true) : [];
        $query = (new MeSendLatterCacheModel());
        $query = $query->select([
            "send_letter_cache_id",
            "company_id",
            "company_id as company_name_str",
//            "letter_ids",
            "letter_status",
            "letter_count",
            "letter_type",
            "letter_status",
            "client_id",
            "type",
            "created_time"
//        ])->where('type',1);
        ]);
        if($filters) {
            if (isset($filters['client_id']) && $filters['client_id']) {
                $query = $query->where('client_id', $filters['client_id']);
            }
        }

        $clientModel = new MeClientModel();


        $data = (new MeSendLatterCacheModel())->getListNoTimeNotStatus($query,$pageSize)->toArray() ?? [];
        foreach($data['data'] as $key=>$value){
            $data['data'][$key]['client_name'] = $clientModel->getByIdNotCompany($value['client_id'],['client_name'])['client_name'] ?? "-";
            $data['data'][$key]['letter_status_str'] = $this->getLetterStatus($value['letter_status']);
            $data['data'][$key]['letter_type_str'] = MeLawCaseLetterConsts::getLetterTypeByType($value['letter_type']);
        }

        return ResponseFunc::returnJson(
            'ok',
            $data,
            '获取发函列表成功',
            ResponseStatusConsts::OK_200_RESPONSE_STATUS
        );
    }

    private function getLetterStatus($status){
        switch ($status){
            case 1:
                return "审核中";
            case 2:
                return "已审核";
            case 3:
                return "纸质函已发函";
            case 4:
                return "电子函已发函";
            case 7:
                return "审核不通过";
        }
    }

    public function approvedLetter($send_letter_cache_id){
        $letterCacheModel = (new MeSendLatterCacheModel());
        $isExists = $letterCacheModel->isExistByCondition([
            'letter_status' => 1
        ]);
        if(!$isExists){
            return ResponseFunc::returnJson(
                'error',
                null,
                '当前状态不允许审批或已审批',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }
        $res = $letterCacheModel->where(
            'send_letter_cache_id', $send_letter_cache_id
        )->update([
            'letter_status' => 2
        ]);
        return ResponseFunc::returnJson(
            'ok',
            null,
            '审核通过',
            ResponseStatusConsts::OK_200_RESPONSE_STATUS
        );
    }

    public function approvedNoPassLetter($send_letter_cache_id){
        $letterCacheModel = (new MeSendLatterCacheModel());
        $isExists = $letterCacheModel->isExistByCondition([
            'letter_status' => 1
        ]);
        if(!$isExists){
            return ResponseFunc::returnJson(
                'error',
                null,
                '当前状态不允许审批或已审批',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }
        $res = $letterCacheModel->where(
            'send_letter_cache_id', $send_letter_cache_id
        )->update([
            'letter_status' => 7
        ]);
        return ResponseFunc::returnJson(
            'ok',
            null,
            '审核不通过',
            ResponseStatusConsts::OK_200_RESPONSE_STATUS
        );
    }


    public function checkSendLetter($send_letter_cache_id){
        $letterCacheModel = (new MeSendLatterCacheModel());
        $letterSendInfo = $letterCacheModel->getAllById($send_letter_cache_id,[
            'letter_status',
            'letter_ids',
            'letter_type',
            'type',
            'letter_status',
        ]);
        if(!$letterSendInfo){
            return ResponseFunc::returnJson(
                'error',
                null,
                '当前调解函不存在',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }

        if($letterSendInfo['letter_status']!=2){
            return ResponseFunc::returnJson(
                'error',
                null,
                '当前调解函审核状态错误',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }
        //暂时先不考虑失败的情况
        //电子函
        if($letterSendInfo['type'] == 1){
            $Key = MeLawCaseListConsts::LAW_LATTER_R_LIST_KEY;
            foreach(explode(',',$letterSendInfo['letter_ids']) as $value){
                Redis::rpush($Key, $value);
            }

            // 修改发函状态
            $status = 4;
        // 纸质函
        }else if($letterSendInfo['type'] == 2){
            $Key = MeLawCaseListConsts::LAW_LATTER_R_LIST_ZZ_KEY;
            foreach(explode(',',$letterSendInfo['letter_ids']) as $value){
                Redis::rpush($Key, $value);
            }
            $status = 3;
        }else{
            return ResponseFunc::returnJson(
                'error',
                null,
                '调解函类型错误',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }
        $res = $letterCacheModel->where(
            'send_letter_cache_id', $send_letter_cache_id
        )->update([
            'letter_status' => $status
        ]);
        return ResponseFunc::returnJson(
            'ok',
            null,
            '确认发函成功',
            ResponseStatusConsts::OK_200_RESPONSE_STATUS
        );
    }


    public function auditSendLetterProcessNext($letterCacheId){
        $letterCacheModel = (new MeSendLatterCacheModel());
        $letterCacheInfo = $letterCacheModel->getAllById($letterCacheId,[
            'letter_ids',
            'preview_info'
        ]);
        if(!$letterCacheInfo){
            return ResponseFunc::returnJson(
                'error',
                null,
                '当前缓存不存在',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }

        if(!$letterCacheInfo['preview_info']){
            return ResponseFunc::returnJson(
                'error',
                null,
                '未审核！',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }

        try{
            $letterCacheModel->where('send_letter_cache_id',$letterCacheId)
                ->where('preview_info','!=',null)
                ->update([
                    'letter_status' => 2
                ]);
            $meSendLetterCacheBind =  new MeSendLetterCacheBindModel();
            $meSendLetterCacheBind->add([
               'staff' => TokenFuc::getCurrentStaffInfo()['staff_id'],
               'send_letter_cache_id' => $letterCacheId,
            ]);
            return ResponseFunc::returnJson(
                'ok',
                null,
                '审核成功！',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }catch (Exception $exception){
            return ResponseFunc::returnJson(
                'error',
                null,
                '审核失败！',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }


    }



}